<template>
  <view class="">
    <c-navBar :title="user_id ? '修改学生信息' : '学生新增'"></c-navBar>
    <view>
      <CForm
        ref="cForm"
        :type="type"
        :formRules="formRules"
        @submit="submit"
        v-model:formData="formData"
        :formList="formList"
      ></CForm>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue"
import CForm from "@/components/CForm/CForm.vue"
import { onLoad, onUnload, onBackPress } from "@dcloudio/uni-app"
import { addStuForm } from "./data"
import { add, getDetail, editInfo } from "@/apis/studentManagement.js"
const { formField, formList, formRules } = addStuForm
const defaultData = JSON.parse(JSON.stringify(formField))
let formData = ref(JSON.parse(JSON.stringify(formField)))

const cForm = ref(null)
let user_id = ref("")
let type = ref("")
onBackPress(() => {
  formData.value = JSON.parse(JSON.stringify(defaultData))
})
onLoad((options) => {
  user_id.value = options.userId
  type.value = options.type
  if (user_id.value) {
    getStuDetail()
  }
})
const getStuDetail = () => {
  getDetail({ user_id: user_id.value }).then((res) => {
    if (res.code === 1) {
      formData.value = res.data || {}
    }
  })
}
const submit = () => {
  if (user_id.value) {
    editStu()
  } else {
    addStu()
  }
}

const addStu = () => {
  console.log(formData.value)
  add(formData.value).then((res) => {
    if (res.code === 1) {
      uni.showSuccessToast("添加成功！")
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        })
      }, 1500)
    }
  })
}

const editStu = () => {
  editInfo({
    ...formData.value,
    user_id: user_id.value
  }).then((res) => {
    if (res.code === 1) {
      uni.showSuccessToast("修改成功！")
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        })
      }, 1500)
    }
  })
}
</script>

<style></style>
